
import RSA from 'node-rsa';

class RsaUtils {
    // 公钥加密
    public static encryptWithPublicKey(key: RSA.Key, message: string) {
        const buffer = Buffer.from(message, 'utf8');
        const encrypted = new RSA(key).encrypt(buffer);
        return encrypted.toString('base64');
    };

    // 共钥解密
    public static decryptWithWithPublicKey(key: RSA.Key, encryptedMessage: string) {
        const buffer = Buffer.from(encryptedMessage, 'base64');
        const decrypted = new RSA(key).decryptPublic(buffer);
        return decrypted.toString('utf8');
    };

    // 私钥加密  
    public static encryptWithPrivateKey(key: RSA.Key, message: string) {
        const buffer = Buffer.from(message, 'utf8');
        const encrypted = new RSA(key).encryptPrivate(buffer);
        return encrypted.toString('base64');
    };
    // 私钥解密
    public static decryptWithPrivateKey(key: RSA.Key, encryptedMessage: string) {
        const buffer = Buffer.from(encryptedMessage, 'base64');
        const decrypted = new RSA(key).decrypt(buffer);
        return decrypted.toString('utf8');
    };
}

export default RsaUtils;